﻿/*
 * 由SharpDevelop创建。
 * 用户： PC
 * 日期: 2025/5/8
 * 时间: 16:38
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace HttpNet
{
	/// <summary>
	/// 网络服务
	/// </summary>
	public class HttpNet
	{
		public class URLData {
			public string method;	// 请求方式，get，post
			public string id;		// 回传套接字
			public string url;		// 请求网址
			public string exdata;	// 附加参数
		}
		
		private static HttpNet instance;
		
		private BDSCSBox.DataAdapter handle = null;
		
		//private BDSCSBox.TYPES.F_FUNC onreceive = null;
		private BDSCSBox.TYPES.F_FUNC onsend = null;
		
		string HttpGet(string url, string exdata) {
			if (!string.IsNullOrEmpty(exdata))
				url = url + "?" + exdata;
			HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
			r.Method = "GET";
			var rp = r.GetResponse();
			var rs = rp.GetResponseStream();
			var rd = new StreamReader(rs, Encoding.UTF8);
			var data = rd.ReadToEnd();
			rd.Close();
			rs.Close();
			rp.Close();
			return data;
		}
		
		string HttpPost(string url, string exdata) {
			HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
			r.Method = "POST";
			if (!string.IsNullOrEmpty(exdata)) {
				var txtbytes = Encoding.UTF8.GetBytes(exdata);
				using (var stm = r.GetRequestStream()) {
					stm.Write(txtbytes, 0, txtbytes.Length);
				}
			}
			var rp = r.GetResponse();
			var rs = rp.GetResponseStream();
			var rd = new StreamReader(rs, Encoding.UTF8);
			var data = rd.ReadToEnd();
			rd.Close();
			rs.Close();
			rp.Close();
			return data;
		}
		
		// 截断数组
		ArrayList GetSeparateSubString(string txtString, int charNumber)
		{
		    ArrayList arrlist = new ArrayList();
		    string tempStr = txtString;
		    if (!string.IsNullOrEmpty(tempStr))
			    for (int i = 0; i < tempStr.Length; i += charNumber)
			    {
			        if ((tempStr.Length - i) > charNumber)//如果是，就截取
			        {
			            arrlist.Add(tempStr.Substring(i, charNumber));
			        }
			        else
			        {
			            arrlist.Add(tempStr.Substring(i));//如果不是，就截取最后剩下的那部分
			        }
			    }
		    return arrlist;
		}
		
		public string EscapeUnicode(string str) // 将字符串编码为unicode转义序列 (\\uxxxx)
		{
		StringBuilder tmp = new StringBuilder();
		for (int i = 0; i < str.Length; i++)
		{
		ushort uxc = (ushort)str[i];
		tmp.Append(@"\u" + uxc.ToString("x4"));
		}
		return tmp.ToString();
		}
		
		private HttpNet(BDSCSBox.DataAdapter h){
			handle = h;
			// 添加默认协议列表
			ServicePointManager.SecurityProtocol |= (SecurityProtocolType.Tls|SecurityProtocolType.Tls11|
			                                         SecurityProtocolType.Tls12);
			// 忽略证书认证
			ServicePointManager.ServerCertificateValidationCallback = (o,xc,xce,err)=>true;
			
			onsend = (msg) => {
				if (msg.Trim().ToLower().IndexOf("jsurl") == 0) {
					var msgs = msg.Trim().Split(' ');
					if (msgs[0].ToLower() == "jsurl") {
						var mainmsg = msg.Trim();
						var submsg = msg.Substring(5).Trim();
						try {
							var ser = new JavaScriptSerializer();
							var d = ser.Deserialize<URLData>(submsg);
							if (d != null) {
								string id = d.id;
								string httpdata = null;
								if (d.method.ToLower() == "get") {
									httpdata = HttpGet(d.url, d.exdata);
								} else if (d.method.ToLower() == "post") {
									httpdata = HttpPost(d.url, d.exdata);
								}
								var httpdatas = GetSeparateSubString(httpdata, 200);
								foreach (string t in httpdatas) {
									// 分段发送
									string cmd = "scriptevent " + id + " " + EscapeUnicode(ser.Serialize(new {
										flag = 1,msg = t
									                                                                     }));
									handle.sendMsg(cmd);
								}
								string endcmd = "scriptevent " + id + " " + EscapeUnicode(ser.Serialize(new {
										flag = 0,msg = "END"
									                                                                     }));
								handle.sendMsg(endcmd);
							}
						} catch(Exception ex){Console.WriteLine(ex.Message + "|" + ex.StackTrace);}
						return false;
					}
				}
				return true;
			};
			h.addDataSender(onsend);
		}
		
		public static void getInstance(BDSCSBox.DataAdapter h) {
			instance = new HttpNet(h);
		}
	}
}

namespace BDSCSBox {
	public class CSL {
		public bool onStart(BDSCSBox.DataAdapter handle) {	// dll入口，注册所有函数
			HttpNet.HttpNet.getInstance(handle);
			Console.WriteLine("[HttpNet] 网络后台指令jsurl已加载。");
			return true;
		}
	}
}